package com.hutou.chuangke.widget.banner;

import java.lang.ref.WeakReference;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * Banner 控件
 *
 * @author peter_wang
 * @create-time 15/4/4 15:58
 */
public class BannerViewPager extends ViewPager {
    public static final int TIMING_MESSAGE = 0;
    //滚动间隔时间，单位 ms
    public static final int SCROLL_INTERVAL = 5000;

    public static final String EXCEPTION_VIEWPAGER_ADAPTER_WRONG = "view pager adapter should be BannerPagerAdapter";

    private BannerPagerAdapter mAdapter;
    private TimingHandler mHandler = new TimingHandler(this);
    private int mScrollInterval = SCROLL_INTERVAL;

    public BannerViewPager(Context context) {
        super(context);
    }

    public BannerViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        getParent().requestDisallowInterceptTouchEvent(true);
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public void setAdapter(PagerAdapter adapter) {
        super.setAdapter(adapter);
        if (!(adapter instanceof BannerPagerAdapter)) {
            throw new RuntimeException(EXCEPTION_VIEWPAGER_ADAPTER_WRONG);
        }
        mAdapter = (BannerPagerAdapter) adapter;
    }

    public void startAutoScroll(){
        mHandler.removeMessages(TIMING_MESSAGE);
        mHandler.sendEmptyMessage(TIMING_MESSAGE);
    }

    /**
     * 设置自动滚动时间
     * @param scrollInterval 单位ms(毫秒)
     */
    public void setScrollInterval(int scrollInterval) {
        mScrollInterval = scrollInterval;
    }

    private void toNextPage() {
        //页数不超过1页不进行轮询
        if (mAdapter.getActualCount()<=1) {
            return;
        }

        int currentIndex = getCurrentItem();
        setCurrentItem(currentIndex + 1);
    }

    private void sendScrollMessage(){
        mHandler.removeMessages(TIMING_MESSAGE);
        mHandler.sendEmptyMessageDelayed(TIMING_MESSAGE,mScrollInterval);
    }

    private class TimingHandler extends Handler {
        private final WeakReference<BannerViewPager> mViewPager;
        private TimingHandler(BannerViewPager viewPager){
            this.mViewPager = new WeakReference<BannerViewPager>(viewPager);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TIMING_MESSAGE:
                    BannerViewPager pager = mViewPager.get();
                    if (pager!=null) {
                        pager.toNextPage();
                        pager.sendScrollMessage();
                    }
                    break;
            }
        }
    }
}
